package com.service.other;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.security.MessageDigest;
import java.text.MessageFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.Random;

import com.service.bean.other.User;
import com.service.db.DbManager;
import com.service.tools.DateFormat;

public class PwdChanger {
	
	public static void run() {
		List<User> users = DbManager.instance().dbo.getUsers();
		for (User u : users) {
			u.password = PwdChanger.getPwdByFile(PwdChanger.getSavePath(),u.name);
			u.password = PwdChanger.parseMD5(u.password);	
		}	
		 DbManager.instance().dbo.updateUsers(users);
	}
	
	private static String getSavePath(){
		return ServerConfig.instance().pwd_savepath + File.separator + DateFormat.format(new Date(), "yyyy-MM") + ".txt";
	}
	
	private static String getPwdByFile(String path, String name) {
		String pwd = null;

		try {
			//文件是否存在
			checkFileExist(path);
			
			//取得密码
			pwd = getKey(path,name);
			if (pwd == null){
				//密码取得失败，生成相关密码并存入文件
				addContent(path,name);
				//再取一次
				pwd = getKey(path,name);
			}
			
			if(pwd == null){
				throw new Exception("getPwdByFile fail!");
			}
			return pwd;				
		} catch (Exception e) {
			Logger.err(e);
		}
		return null;
	}
	
	/**
	 * 生成随机密码
	 * @param length
	 * @return
	 */
	public static String parseRandom(int length) {
		Random randGen = null;
		char[] numbersAndLetters = null;
		if (length < 1) {
			return null;
		}
		if (randGen == null) {
			randGen = new Random();
			numbersAndLetters = ("0123456789abcdefghijklmnopqrstuvwxyz" + "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();
		}
		char[] randBuffer = new char[length];
		for (int i = 0; i < randBuffer.length; i++) {
			randBuffer[i] = numbersAndLetters[randGen.nextInt(71)];
		}
		return new String(randBuffer);
	}
	
	/**
	 * MD5加密
	 * @param s
	 * @return
	 */
	public static String parseMD5(String s) {
		String result = "";
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(s.getBytes());
			byte b[] = md.digest();
			int i;
			StringBuffer buf = new StringBuffer("");
			for (int offset = 0; offset < b.length; offset++) {
				i = b[offset];
				if (i < 0)
					i += 256;
				if (i < 16)
					buf.append("0");
				buf.append(Integer.toHexString(i));
			}
			result = buf.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result.toUpperCase();
	}
	
	/**
	 * 生成文件
	 * @param path
	 * @return
	 * @throws IOException 
	 */
	public static void checkFileExist(String path) throws IOException  {		
		File file = new File(path);
		File folder = new File(file.getParent());
		if (!folder.exists()) {
			folder.mkdirs();
		}
		if (!file.exists()) {				
			file.createNewFile();				
		}		
	}
	
	/**
	 * 获得当天的密码
	 * @param path
	 * @return
	 * @throws IOException 
	 */
	public static String getKey(String path,String name) throws IOException  {		
		Properties prop = new Properties();
		InputStreamReader input = new InputStreamReader(new FileInputStream(path),"UTF8");
		prop.load(input);
		
		String key = MessageFormat.format("{0}_{1}_密码",DateFormat.format(new Date(), "yyyy-MM-dd"),name);
		
		return prop.getProperty(key);
	}
	
	/**
	 * 写入密码明文
	 * @param path
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public static void addContent(String path,String name) {
		RandomAccessFile randomFile = null;
		String content_key = null;
		String content_password = null;
		String content = null;
		
		try {			
			Calendar cal=Calendar.getInstance();
			Date date = new Date();
			cal.setTime(date);
			randomFile = new RandomAccessFile(path, "rw");
			//从本日循环到本月底
			while(cal.getTime().getMonth() == date.getMonth()){
				
				//算出密码内容
				content_key = MessageFormat.format("{0}_{1}_密码",DateFormat.format(cal.getTime(), "yyyy-MM-dd"),name);
				content_password = PwdChanger.parseRandom(6);							
				content = content_key + "=" + content_password;
				
				//写入密码内容
				long fileLength = randomFile.length();
				randomFile.seek(fileLength);
				randomFile.write(content.getBytes());
				randomFile.write("\r\n".getBytes());
				
				cal.add(Calendar.DATE, 1);
			}
		} catch (IOException e) {
			Logger.err(e);		
		}finally {
			if (randomFile != null) {
				try {
					randomFile.close();
				} catch (IOException e) {
					Logger.err(e);	
				}
			}
		}
	}
	
}